<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="菜品信息" name="first">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
                 label-width="80px">
          <el-form-item label="菜品名称" prop="foodName">
            <el-input v-model="dataForm.foodName" placeholder="菜品名称"></el-input>
          </el-form-item>
          <el-form-item label="所属分类" prop="typeId">
            <el-select v-model="dataForm.typeId">
              <el-option
                v-for="item in fenleiList"
                :label="item.classificationName"
                :key="item.id"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="简码" prop="shortCode">
            <el-input v-model="dataForm.shortCode" placeholder="简码(菜品首字母大写,如啤酒鸭为PJY)"></el-input>
          </el-form-item>
          <el-form-item label="菜品价钱" prop="price">
            <el-input v-model="dataForm.price" placeholder="菜品价钱"></el-input>
          </el-form-item>
          <!--  <el-form-item label="会员价" prop="memberPrice">
              <el-input v-model="dataForm.memberPrice" placeholder="会员价"></el-input>
            </el-form-item> -->
          <el-form-item label="成本价" prop="costPrice">
            <el-input v-model="dataForm.costPrice" placeholder="成本价"></el-input>
          </el-form-item>
          <!--  <el-form-item label="提成" prop="bommission">
              <el-input v-model="dataForm.bommission" placeholder="提成"></el-input>
            </el-form-item> -->
          <el-form-item label="菜品别名" prop="foodAlias">
            <el-input v-model="dataForm.foodAlias" placeholder="菜品别名"></el-input>
          </el-form-item>
          <!-- <el-form-item label="规格" prop="norms">
             <el-input v-model="dataForm.norms" placeholder="规格"></el-input>
           </el-form-item> -->
          <el-form-item label="口味备注" prop="flavorReamark">
            <el-input v-model="dataForm.flavorReamark" placeholder="口味备注"></el-input>
          </el-form-item>
          <el-form-item label="菜品介绍" prop="foodReamark">
            <el-input v-model="dataForm.foodReamark" placeholder="菜品介绍"></el-input>
          </el-form-item>
          <el-form-item label="菜品图片" prop="foodImg">
            <el-upload
              class="avatar-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="dataForm.foodImg" :src="dataForm.foodImg" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <!--        <el-upload-->
            <!--          :file-list="fileList"-->
            <!--          list-type="picture-card"-->
            <!--          :action="uploadAction"-->
            <!--          :on-preview="handlePictureCardPreview"-->
            <!--          :on-success="handleImageSuccess"-->
            <!--          :on-remove="handleImageRemove"-->
            <!--          :before-upload="beforeAvatarUpload"-->
            <!--        >-->
            <!--          <i class="el-icon-plus"></i>-->
            <!--        </el-upload>-->
            <!--        <img v-if="dataForm.id > 0" style="width: 200px;height: 160px" :src="dataForm.foodImg"/>-->
          </el-form-item>
          <!-- <el-form-item label="启用称重" prop="enableWeigh">
           <el-radio v-model="dataForm.enableWeigh" label="1">是</el-radio>
           <el-radio v-model="dataForm.enableWeigh" label="2">否</el-radio>
           </el-form-item>
           <el-form-item label="启用开台预定" prop="enableOpenReserve">
             <el-radio v-model="dataForm.enableOpenReserve" label="1">是</el-radio>
             <el-radio v-model="dataForm.enableOpenReserve" label="2">否</el-radio>
           </el-form-item>
           <el-form-item label="最低折扣" prop="minDiscount">
             <el-input v-model="dataForm.minDiscount" placeholder="最低折扣"></el-input>
           </el-form-item> -->
          <el-form-item v-show="dataForm.id == 0" label="使用范围" prop="useRangeList">
            <el-checkbox-group v-model="dataForm.useRangeList">
              <el-checkbox v-for="range in useRangeList" :key="range.id" :label="range.id">{{
                  range.orderName
                }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="规格设置" name="second">
        <FoodSpecs  @getSpecsList="getSpecsList" ref="FoodSpecsRef"></FoodSpecs>
      </el-tab-pane>
      <el-tab-pane label="口味设置" name="third">
        <FoodFlavor  @getFlavorList="getFlavorList" ref="FoodFlavorRef"></FoodFlavor>
      </el-tab-pane>
    </el-tabs>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :disabled="disabledSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import FoodSpecs from './food_specs'
import FoodFlavor from './food_flavor'
export default {
  components:{
    FoodSpecs,
    FoodFlavor
  },

  data() {
    return {
      activeName:'first',
      fenleiList: [],
      img: '',
      index: null,
      showImage: [],
      fileList: [],
      uploadAction: '',
      visible: false,
      disabledSubmit: false,
      dataForm: {
        id: 0,
        foodNo: '',
        sellerId: '',
        foodName: '',
        typeId: '',
        shortCode: '',
        sort: '',
        price: '',
        memberPrice: '',
        weixinMemberPrice: '',
        costPrice: '',
        bommission: '',
        foodAlias: '',
        status: '',
        norms: '',
        flavorReamark: '',
        foodReamark: '',
        foodImg: '',
        enableWeigh: '',
        enableOpenReserve: '',
        stock: '',
        minDiscount: '',
        remark: '',
        useRangeList: [1, 2, 3]
      },
      useRangeList: [],
      dataRule: {
        foodNo: [
          {required: true, message: '菜品编号不能为空', trigger: 'blur'}
        ],

        foodName: [
          {required: true, message: '菜品名称不能为空', trigger: 'blur'}
        ],
        typeId: [
          {required: true, message: '所属分类不能为空', trigger: 'blur'}
        ],
        norms: [
          {required: true, message: '规格不能为空', trigger: 'blur'}
        ],

        shortCode: [
          {required: true, message: '简码不能为空', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '价格不能为空', trigger: 'blur'}
        ],
        useRangeList: [
          {required: true, message: '使用范围不能为空', trigger: 'blur'}
        ]
      },
      flavorList:{
		  moreFlavor:false
	  },
      specsList:{
		  moreSpecs:false
	  },
      nullSpecsSign:0,
      nullFlavorSign:0,
    }
  },
  activated() {

  },
  methods: {
    //获取规格列表
    getSpecsList(info){
      this.specsList = info
    },
    getFlavorList(info){
      this.flavorList = info
    },
    //预览
    handlePictureCardPreview(file) {
      this.index = 0;
      this.showImage = file.url;
    },
    getImgs(img) {
      return (img || '')
        .split(',')
        .filter(url => !!url)
        .map(url => ({
          name: url,
          url
        }));
    },
    onEditorBlur() {
    },
    onEditorFocus() {
      //获得焦点事件
    },
    onEditorChange() {
      //内容改变事件
    },
    handleClose(tag) {
      this.dataForm.tagList.splice(this.dataForm.tagList.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dataForm.tagList.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleAvatarSuccess(res, file) {
      this.dataForm.ewmLogo = res.url;
    },

    handleImageSuccess(res, file, fileList) {
      if (res.code === 0){
        this.$message.success("图片上传成功")
        this.dataForm.foodImg = res.url
      }else {
        this.$message.success("图片上传失败")
      }

    },
    handleImageRemove(file, fileList) {
      this.handleImageSuccess({}, file, fileList);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    init(id) {
      this.uploadAction = this.$http.adornUrl(`/sys/oss/upload?token=${this.$cookie.get('token')}`);
      //分类
      this.$http({
        url: this.$http.adornUrl('/store/tstorefoodtype/list'),
        method: 'get',
        params: this.$http.adornParams({
          'status': 1,
          'page': 1,
          'limit': 1000,
          'key':''
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.fenleiList = data.page.list
        } else {
          this.fenleiList = []
          this.totalPage = 0
        }
      })
      this.$http({
        url: this.$http.adornUrl('/store/tstoreordermode/list'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({data}) => {
        this.useRangeList = data.page.list
      })
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/store/tstorefood/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              var arr = []
              this.dataForm.foodNo = data.tStoreFood.foodNo
              this.dataForm.sellerId = data.tStoreFood.sellerId
              this.dataForm.foodName = data.tStoreFood.foodName
              this.dataForm.typeId = data.tStoreFood.typeId
              this.dataForm.shortCode = data.tStoreFood.shortCode
              this.dataForm.sort = data.tStoreFood.sort
              this.dataForm.price = data.tStoreFood.price
              this.dataForm.memberPrice = data.tStoreFood.memberPrice
              this.dataForm.weixinMemberPrice = data.tStoreFood.weixinMemberPrice
              this.dataForm.costPrice = data.tStoreFood.costPrice
              this.dataForm.bommission = data.tStoreFood.bommission
              this.dataForm.foodAlias = data.tStoreFood.foodAlias
              this.dataForm.status = data.tStoreFood.status
              this.dataForm.norms = data.tStoreFood.norms
              this.dataForm.flavorReamark = data.tStoreFood.flavorReamark
              this.dataForm.foodReamark = data.tStoreFood.foodReamark
              this.dataForm.foodImg = data.tStoreFood.foodImg
              this.dataForm.enableWeigh = data.tStoreFood.enableWeigh.toString()
              this.dataForm.enableOpenReserve = data.tStoreFood.enableOpenReserve.toString()
              this.dataForm.stock = data.tStoreFood.stock
              this.dataForm.minDiscount = data.tStoreFood.minDiscount
              this.dataForm.remark = data.tStoreFood.remark
              this.$refs.FoodSpecsRef.initData(data.tStoreFood)
              this.$refs.FoodFlavorRef.initData(data.tStoreFood)
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      //启用多规格
      // if (this.specsList.moreSpecs === true){
      //   //判断多规格是否输入正确
      //   for (let i = 0 ; i < this.specsList.data.length ; i++){
      //     let item = this.specsList.data[i]
      //     if (item.specsName === '' || item.price === '' || item.costPrice === ''){
      //       this.$message.warning("规格输入不完整")
      //       this.nullSpecsSign = 1
      //       break;
      //     }
      //   }
      // }else {
      //   if (this.specsList === '' ){
      //     this.dataForm.norms = '份'
      //   }else {
      //     this.dataForm.norms = this.specsList.specs
      //   }
      // }
      //
      // //启用多口味
      // if (this.flavorList.moreFlavor === true){
      //   for (let i = 0 ; i < this.flavorList.data.length ; i++){
      //     let item = this.flavorList.data[i]
      //     if (item.flavorName === ''){
      //       this.$message.warning("口味输入不完整")
      //       this.nullFlavorSign = 1
      //       break;
      //     }
      //   }
      // }

      if (this.nullSpecsSign !== 1 && this.nullFlavorSign !== 1){
        this.disabledSubmit = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/store/tstorefood/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'foodNo': this.dataForm.foodNo,
                'sellerId': this.dataForm.sellerId,
                'foodName': this.dataForm.foodName,
                'typeId': this.dataForm.typeId,
                'shortCode': this.dataForm.shortCode,
                'sort': this.dataForm.sort,
                'price': this.dataForm.price,
                'memberPrice': this.dataForm.memberPrice,
                'weixinMemberPrice': this.dataForm.weixinMemberPrice,
                'costPrice': this.dataForm.costPrice,
                'bommission': this.dataForm.bommission,
                'foodAlias': this.dataForm.foodAlias,
                'status': this.dataForm.status,
                'norms': this.dataForm.norms,
                'flavorReamark': this.dataForm.flavorReamark,
                'foodReamark': this.dataForm.foodReamark,
                'foodImg': this.dataForm.foodImg,
                'enableWeigh': this.dataForm.enableWeigh,
                'enableOpenReserve': this.dataForm.enableOpenReserve,
                'stock': this.dataForm.stock,
                'minDiscount': this.dataForm.minDiscount,
                'remark': this.dataForm.remark,
                'useRangeList': this.dataForm.useRangeList,
                'specsList': this.specsList.data,
                'flavorList': this.flavorList.data,
                'normsStatus': this.specsList.moreSpecs===false?2:1,
                'flavorStatus': this.flavorList.moreFlavor===false?2:1
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.disabledSubmit = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
                this.disabledSubmit = false
              }
            })
          } else {
            this.disabledSubmit = false
          }
        })
      }
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
